<?php


namespace Beerus\Modules\Album\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\Album\AlbumListModel;
use Biz\model\Album\AlbumTagClassifyMappingModel;
use Biz\model\ShopCategoryClassify;
use Biz\service\Album\AlbumListService;
use Biz\service\Album\AlbumTagClassifyMappingService;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Exception;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class AlbumTagClassifyMappingController extends Controller
{
    const PAGE_SIZE = 20;

    public function index(Request $request, Content $content)
    {
        $allCategory = ShopCategoryClassify::selectByWhere(['cate_id' => 0, 'status' => 1]);
        $allCategoryTree = AlbumTagClassifyMappingService::getTree($allCategory);
        $cateList = AlbumTagClassifyMappingService::getClassifyList($allCategoryTree);
        $id = $request->input('id', 0);
        $classifyId = $request->input('classify_id', '');
        if ($id == 0) {
            $id = $classifyId;
        }
        $data = [];
        //查询标签和分类的关系（所有的）
        $tagMappingList = AlbumTagClassifyMappingModel::selectByWhere(['status' => AlbumTagClassifyMappingModel::STATUS_NORMAL]);
        $classifyTagMap = [];
        if ($tagMappingList) {
            //根据classify_id对标签进行分组
            foreach ($tagMappingList as $tagMapping) {
                $classifyTagMap[$tagMapping['classify_id']][] = $tagMapping['tag'];
            }
        }

        if ($cateList) {
            $cateInfo = [];
            $ids = [];
            if ($id > 0) {
                $ids = [(int)$id];
                $mapping = AlbumTagClassifyMappingService::getTree($allCategory, $id);
                $mappingList = AlbumTagClassifyMappingService::getClassifyList($mapping);
                $ids = array_merge($ids, array_keys($mappingList));
            }
            foreach ($cateList as $key => $cate) {
                $cateInfo['classify_id'] = $key;
                $cateInfo['classify_name'] = $cate;
                //关联的标签
                $cateInfo['tags'] = $classifyTagMap[$key] ?? [];
                $cateInfo['tags_count'] = count($classifyTagMap[$key] ?? []);
                if (!empty($ids)) {
                    if (in_array($key, $ids)) {
                        $data[] = $cateInfo;

                    }
                } else {
                    $data[] = $cateInfo;

                }
            }
            $tagsCount = array_column($data, 'tags_count');
            array_multisort($tagsCount, SORT_DESC, $data);
        }
        $total = count($data);

        //查询标签列表
        $gridModel = new pGridDataModel($data, $total, ['perPage' => 999]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $cateList) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableCreateButton();
            $grid->filter(function (Grid\Filter $filter) use ($cateList) {
                $filter->disableIdFilter();
                $filter->equal('id', '分类id');
                $filter->equal('classify_id', '分类')->select($cateList);
                //条件展开
                $filter->expand();
            });
            $grid->column('classify_id', '好物分类id');
            $grid->column('classify_name', '好物分类名称');
            $grid->column('tags_count', '关联的标签个数')->display(function () {

                return "<span style='color:blue'>$this->tags_count</span>";
            });
            $grid->column('tags', '关联的标签')->display(function () {
                $html = "<ol>";
                if ($this->tags) {
                    foreach ($this->tags as $tag) {
                        $html .= "<li style='color: green'>$tag</li>";
                    }
                }
                $html."</ol>";

                return $html;

            });
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->append('&nbsp;&nbsp;<a class="fa" href="'.url('admin/album/tagMapping/create?classify_id='.$actions->row->classify_id).'">编辑</a>');
            });

        });

        $tab = new Tab();
        $tab->add('清单标签映射列表', $grid->render(), true);
        $content->row($tab);

        return $content
            ->header("好物清单 | 清单标签映射管理");
    }

    public function create(Content $content, Request $request): Content
    {
        $classifyId = $request->input('classify_id');
        $data = [];
        $tagList = AlbumListService::getTagList(['description' => AlbumListModel::TAG_MAPPING_NAME]);
        if ($classifyId) {
            $data['classify_id'] = $classifyId;
            $tags = [];
            $tagMappingList = AlbumTagClassifyMappingModel::selectByWhere([
                'status' => AlbumTagClassifyMappingModel::STATUS_NORMAL,
                'classify_id' => $classifyId,
            ], 'tag');
            if ($tagMappingList) {
                foreach ($tagList as $item) {
                    if (in_array(explode('|', $item)[1], $tagMappingList)) {
                        $tags[$item] = $item;
                    }
                }
            }
            $data['tag_list'] = $tags;
        }
        $title = '编辑';
        $form = new Form($data);
        $form->hidden('classify_id');
        $form->multipleSelect('tag_list', '关联的清单标签')->options(array_combine($tagList, $tagList));

        $form->confirm('确定提交吗？', 'add');
        $form->action('/admin/album/tagMapping/save');

        $tab = new Tab();
        $tab->add($title, $form->render(), true);
        $tab->addLink('清单标签映射列表', url("/admin/album/tagMapping/index"), false);
        $content->row($tab);

        return $content
            ->header("清单标签映射关系管理 | $title");
    }

    public function save(Request $request): RedirectResponse
    {
        $classifyId = $request->input('classify_id', 0);
        $tagList = array_filter($request->input('tag_list', []));//标签列表
        try {
            $tagNames = [];
            if (!empty($tagList)) {
                foreach ($tagList as $tagInfo) {
                    $tagNames [] = explode('|', $tagInfo)[1] ?? '';
                }
            }

            $result = AlbumTagClassifyMappingService::saveTagMapping($classifyId, $tagNames, Admin::user()->id);
            if (!$result) {
                throw new Exception('分类编辑失败');
            }

            return redirect('/admin/album/tagMapping/index');
        } catch (Exception $e) {
            Log::error('活动编辑失败', $e->getMessage());
            $error = new MessageBag([
                'title' => '编辑失败,'.$e->getMessage(),
            ]);

            return back()->with(compact('error'));
        }

    }

}